package com.rabbiter.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.common.QueryPageParam;
import com.rabbiter.common.Result;
import com.rabbiter.entity.Goods;
import com.rabbiter.service.GoodsService;
import com.rabbiter.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器：物品管理
 * </p>
 */
@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Resource
    private MinioUtil minioUtil;

    /*
     * 新增物品
     */
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods) {
        try {
            goodsService.saveAll(goods);
            return Result.success("新增商品成功");
        } catch (Exception e) {
            log.warn(e.getMessage());
            return Result.fail("新增商品失败");
        }
    }

    /*
     * 更新物品
     */
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods){
        return goodsService.updateById(goods)?Result.success():Result.fail();
    }

    @RequestMapping("/test")
    public String test(@RequestParam("image") MultipartFile image) throws Exception {
        String URL = minioUtil.uploadFile(image);
        return URL;
    }

    /*
     * 更新商品图片
     */
    @PostMapping("/updateImageById/{id}")
    public Result updateImage(@PathVariable("id") Integer id,
                              @RequestParam("file") MultipartFile image) throws Exception{
        String Url = goodsService.updateImage(id,image);
        return Result.success(Url);
//        try {
//            goodsService.updateImage(id,image);
//            return Result.success("修改图片成功");
//        } catch (Exception e) {
//            log.warn(e.getMessage());
//            return Result.fail("修改图片失败");
//        }
    }

    /*
     * 删除物品
     */
    @GetMapping("/del")
    public Result del(@RequestParam String id){
        return goodsService.removeById(id)?Result.success():Result.fail();
    }

    /*
     * 模糊查询：根据输入查询物品并以分页的形式展示
     */
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        Map<String, String> searchParams = query.getParam();
        String name = searchParams.getOrDefault("name", "");
        String goodstype = searchParams.getOrDefault("goodstype", "");
        String storage = searchParams.getOrDefault("storage", "");

        Page<Goods> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        addLikeCondition(queryWrapper, Goods::getName, name);
        addLikeCondition(queryWrapper, Goods::getGoodstype, goodstype);
        addLikeCondition(queryWrapper, Goods::getStorage, storage);

        IPage<Goods> result = goodsService.pageCC(page, queryWrapper);
        Map<String, Object> responseData = new HashMap<>(); // 使用Map提高类型安全性
        responseData.put("records", result.getRecords());
        responseData.put("total", result.getTotal());
        return Result.success(responseData);
    }

    private void addLikeCondition(LambdaQueryWrapper<Goods> wrapper, SFunction<Goods, ?> column, String value) {
        if (StringUtils.isNotBlank(value) && !"null".equalsIgnoreCase(value)) {
            wrapper.like(column, value);
        }
    }
}
